# _*_ coding:utf-8 _*_
# @File  : short_message.py
# @Time  : 2021-07-30  08:23
# @Author: zizle

import datetime
import hashlib

from fastapi import APIRouter, Depends, Body, Path, Query
from pydantic import BaseModel

from db import FAConnection
from interfaces.depends import admin_logged_require
from status import r_status

stm_api = APIRouter()


class ShortMsgItem(BaseModel):
    create_time: str
    content: str


@stm_api.post('/stm/', summary='添加一条短讯通')
async def post_create_short_message(person: dict = Depends(admin_logged_require), msg_item: ShortMsgItem = Body(...)):
    try:
        create_time = datetime.datetime.strptime(msg_item.create_time, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        return {'code': r_status.VALIDATE_ERROR, 'message': 'create time can not format %Y-%m-%dT%H:%M:%S!'}
    user_id = person['uid']
    content_hash = hashlib.md5(msg_item.content.encode('utf8')).hexdigest()
    sql = 'INSERT IGNORE INTO info_short_message (create_time,creator,content,md5) VALUES (%s,%s,%s,%s);'
    db = FAConnection(conn_name='新建短讯通')
    count, _ = db.insert(sql, [create_time, user_id, msg_item.content, content_hash])
    if count:
        return {'code': r_status.CREATED_SUCCESS, 'message': '创建短讯通成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '创建短讯通失败,原因未知!'}


@stm_api.get('/stm/', summary='查询短讯通')
async def get_short_message(page: int = Query(..., ge=1), page_size: int = Query(..., ge=50, le=200)):  # ism : is admin
    record_start = (page - 1) * page_size
    record_offset = page_size
    sql = 'SELECT SQL_CALC_FOUND_ROWS id,create_time,content,is_active ' \
          'FROM info_short_message ' \
          'ORDER BY create_time DESC LIMIT %s,%s;'
    db = FAConnection(conn_name='分页查询短讯通')
    records = db.query(sql, [record_start, record_offset], keep_conn=True)
    total_obj = db.query('SELECT FOUND_ROWS() AS total;', fetchone=True)
    total_count = total_obj[0]['total'] if total_obj else 0  # 当前总数量
    for item in records:
        item['time_str'] = item['create_time'].strftime('%H:%M')
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')

    return {'code': r_status.SUCCESS, 'message': '查询短讯通成功!', 'page': page, 'page_size': page_size,
            'total_count': total_count, 'data': records}


@stm_api.get('/stm/{query_date}/', summary='查询指定日期短讯通')
async def get_point_date_short_message(query_date: str = Path(...)):
    try:
        query_date = datetime.datetime.strptime(query_date, '%Y-%m-%d')
    except ValueError:
        return {'code': r_status.VALIDATE_ERROR, 'message': '日期格式错误!', 'data': []}
    query_sql = 'SELECT id,create_time,content FROM info_short_message WHERE DATE_FORMAT(create_time,"%%Y-%%m-%%d")=%s;'
    db = FAConnection(conn_name='指定日期短讯通')
    records = db.query(query_sql, [query_date.strftime('%Y-%m-%d')])
    for item in records:
        item['time_str'] = item['create_time'].strftime('%H:%M')
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
    return {'code': r_status.SUCCESS, 'message': '获取短讯通成功!', 'data': records}


@stm_api.put('/stm/{stm_id}/', summary='修改一条短信通')
async def update_short_message(person: dict = Depends(admin_logged_require), stm_id: int = Path(..., ge=1),
                               content: str = Body(..., embed=True)):
    sql = 'UPDATE IGNORE info_short_message SET content=%s,md5=%s WHERE id=%s LIMIT 1;'
    content_hash = hashlib.md5(content.encode('utf8')).hexdigest()
    db = FAConnection(conn_name='修改短讯通')
    success = db.execute(sql, [content, content_hash, stm_id])
    if success:
        return {'code': r_status.CREATED_SUCCESS, 'message': '修改短讯通成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '修改短讯通失败,原因未知!'}


@stm_api.delete('/stm/{stm_id}/', summary='删除一条短讯通')
async def delete_short_message(person: dict = Depends(admin_logged_require), stm_id: int = Path(..., ge=1)):
    sql = 'DELETE FROM info_short_message WHERE id=%s LIMIT 1;'
    db = FAConnection(conn_name='删除短讯通')
    success = db.execute(sql, [stm_id])
    if success:
        return {'code': r_status.CREATED_SUCCESS, 'message': '删除短讯通成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '删除短讯通失败,原因未知!'}
